import {defaultLocale, loadLanguageAsync} from "~/locales";

/**
 * @FileName: auto-lang.ts
 * @Description: // 组合式API用于处理多语言
 * @Author: Ellwood(liugangsin@qq.com)
 * @CreateDate: 2025/2/7 - 11:10
 * @Version: V1.0.0
 */

export const useAppLocale = createGlobalState(() =>
  useStorage("locale", defaultLocale),
);

export const useAutoLang = () => {
  const appLocale = useAppLocale();

  const { locale, getLocaleMessage } = useI18n();

  const setLanguage = async (lang: string) => {
    try {
      await loadLanguageAsync(lang);
      appLocale.value = lang;
      locale.value = lang;
    } catch (e) {
      throw new Error(`Failed to load language: ${lang}`);
    }
  };

  // 获取当前系统的语言
  const { isSupported, language } = useNavigatorLanguage();
  if (isSupported.value) {
    if (language.value !== defaultLocale) {
      setLanguage(language.value!).then(() => {});
    }
    watch(language, () => {
      setLanguage(language.value!).then(() => {});
    });
  } else {
    if (appLocale.value !== defaultLocale) {
      setLanguage(appLocale.value).then(() => {});
    }
  }

  watch(appLocale, (lang) => {
    if (lang && lang !== locale.value) {
      setLanguage(lang).catch(() => {});
    }
  });

  const naiveLocale = computed(
    () => getLocaleMessage(appLocale.value).naiveUI || {},
  );
  return {
    naiveLocale,
    setLanguage,
  };
};
